
#include <string>
#include <cstdlib>
#include <BMap>
#include <BString>

using namespace BWE;

#ifdef linux
#include <unistd.h>
#include <iconv.h>
#include <sys/time.h>

BWEAPI BReal BWE::bTime()
{
	struct timeval tv;
	struct timezone tz;
	gettimeofday(&tv, &tz);
	return tv.tv_sec + tv.tv_usec * 0.000001;
}

BWEAPI bool BWE::bSleep(double seconds)
{
	usleep(seconds * 1000000);
	return true;
}

BWEAPI int BWE::bWcsToMbs(const wchar_t* wstr, char* cstr)
{
	int len = wcslen(wstr);
	const char* loca = setlocale(LC_CTYPE, 0);
	size_t size = wcstombs(cstr, wstr, len + 1);
	cstr[size] = 0;
	return size;
}
BWEAPI int BWE::bMbsToWcs(const char* cstr, wchar_t* wstr)
{
	int len = strlen(cstr);
	const char* loca = setlocale(LC_CTYPE, 0);
	size_t size = mbstowcs(wstr, cstr, len + 1);
	wstr[size] = 0;
	return size;
}

#endif

#ifdef _WIN32
#include <Windows.h>
#undef min
#undef max
#undef near
#undef far

BWEAPI BReal BWE::bTime()
{
	LARGE_INTEGER frequency;
	QueryPerformanceFrequency(&frequency);
	LARGE_INTEGER counter;
	QueryPerformanceCounter(&counter);
	return (BReal)counter.QuadPart / (BReal)frequency.QuadPart;
}

BWEAPI bool BWE::bSleep(BReal seconds)
{
	timeBeginPeriod(1);
	DWORD result = 1;
	if (HANDLE hTimer = CreateWaitableTimerW(NULL, TRUE, NULL))
	{
		LARGE_INTEGER liDueTime;
		liDueTime.QuadPart = (LONGLONG)(seconds * -10000000);
		SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, FALSE);
		result = WaitForSingleObject(hTimer, INFINITE);
		CloseHandle(hTimer);
	}
	timeEndPeriod(1);
	return result == WAIT_OBJECT_0;
}

int BWE::bWcsToMbs(const wchar_t* wstr, char* cstr)
{
	if (!wstr)
		return 0;
	int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, 0, 0, 0, 0);
	if (!cstr)
		return len;
	int end = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, cstr, len, 0, 0);
	return end;
}
int BWE::bMbsToWcs(const char* cstr, wchar_t* wstr)
{
	if (!cstr)
		return 0;
	int len = MultiByteToWideChar(CP_UTF8, 0, cstr, -1, NULL, 0);
	if (!wstr)
		return len;
	int end = MultiByteToWideChar(CP_UTF8, 0, cstr, -1, wstr, len);
	return end;
}

#endif
